package com.ibeetl.cms.web;

import com.ibeetl.admin.console.service.UserConsoleService;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.entity.CoreUserRole;
import com.ibeetl.admin.core.file.FileService;
import com.ibeetl.admin.core.service.CorePlatformService;
import com.ibeetl.admin.core.util.ConvertUtil;
import com.ibeetl.admin.core.util.ValidateConfig;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.cms.entity.ApplyAccount;
import com.ibeetl.cms.entity.Enterprise;
import com.ibeetl.cms.service.ApplyAccountService;
import com.ibeetl.cms.service.EnterpriseService;
import com.ibeetl.cms.util.RoleConstant;
import com.ibeetl.cms.web.query.ApplyAccountQuery;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;
import java.util.List;

/**
 * ApplyAccount 接口
 */
@Controller
public class ApplyAccountController {

    private final Log log = LogFactory.getLog(this.getClass());
    private static final String MODEL = "/cms/applyAccount";


    @Autowired private ApplyAccountService applyAccountService;


    @Autowired
    CorePlatformService platformService;
    
    @Autowired
    FileService fileService;

    @Autowired
    UserConsoleService userConsoleService;

    @Autowired
    private EnterpriseService enterpriseService;

    @GetMapping(MODEL + "/index.do")
    @Function("cms.applyAccount.edit")
    @ResponseBody
    public ModelAndView index() {
        ModelAndView view = new ModelAndView("/cms/applyAccount/index.html") ;
        view.addObject("search", ApplyAccountQuery.class.getName());
        return view;
    }

    @GetMapping(MODEL + "/edit.do")
    @Function("cms.applyAccount.edit")
    @ResponseBody
    public ModelAndView edit(Integer id) {
        ModelAndView view = new ModelAndView("/cms/applyAccount/edit.html");
        ApplyAccount applyAccount = applyAccountService.queryById(id);
        view.addObject("applyAccount", applyAccount);
        return view;
    }

    @GetMapping(MODEL + "/add.do")
    @ResponseBody
    public ModelAndView add() {
        ModelAndView view = new ModelAndView("/cms/applyAccount/add.html");
        return view;
    }

    /* ajax json */

    @PostMapping(MODEL + "/list.json")
    @Function(value="cms.applyAccount.query", name="企业申请开户列表")
    @ResponseBody
    public JsonResult<PageQuery> list(ApplyAccountQuery condtion)
    {
        PageQuery page = condtion.getPageQuery();
        applyAccountService.queryByCondition(page);
        return JsonResult.success(page);
    }

    @PostMapping(MODEL + "/add.json")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)ApplyAccount applyAccount)
    {
        applyAccountService.save(applyAccount);
        return new JsonResult().success();
    }

    @PostMapping(MODEL + "/update.json")
    @Function(value = "cms.applyAccount.update", name="企业申请开户受理通过")
    @ResponseBody
    public JsonResult<CoreUser> update(@Validated(ValidateConfig.UPDATE.class)  ApplyAccount applyAccount) {
        applyAccount.setState("1");
        boolean success = applyAccountService.updateTemplate(applyAccount);

        /**
         * 开户操作
         */

        CoreUser newUser = new CoreUser();
        newUser.setCode(applyAccount.getPhone());
        newUser.setName(applyAccount.getCompanyName());
        newUser.setNeedInfo("0");
        newUser.setOrgId((long) 1);
        newUser.setCreateTime(new Date());
        newUser.setPassword("abc123");
        newUser.setRoleId(RoleConstant.COMPANY);
        userConsoleService.saveUser(newUser);

        /**
         * 建立用户-角色对应关系
         */
        CoreUserRole coreUserRole = new CoreUserRole();
        coreUserRole.setUserId(newUser.getId());
        coreUserRole.setRoleId(RoleConstant.COMPANY);
        coreUserRole.setOrgId((long) 1);

        userConsoleService.saveUserRole(coreUserRole);

        /**
         * 在企业基本信息中插入一条记录
         */
        Enterprise enterprise = new Enterprise();
        enterprise.setUserId(Math.toIntExact(newUser.getId()));
        enterprise.setEnterpriseName(applyAccount.getCompanyName());
        enterprise.setOrganizationCode(applyAccount.getCompanyCode());

        enterpriseService.save(enterprise);
        if (success) {
            platformService.clearFunctionCache();
            platformService.clearMenuCache();

            return JsonResult.success(newUser);
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }


   
    @GetMapping(MODEL + "/view.json")
    @Function("cms.applyAccount.query")
    @ResponseBody
    public JsonResult<ApplyAccount>queryInfo(Integer id) {
        ApplyAccount applyAccount = applyAccountService.queryById( id);
        return  JsonResult.success(applyAccount);
    }

    @PostMapping(MODEL + "/delete.json")
    @Function(value="cms.applyAccount.delete", name="删除企业申请开户请求")
    @ResponseBody
    public JsonResult delete(String ids) {
        if (ids.endsWith(",")) {
            ids = StringUtils.substringBeforeLast(ids, ",");
        }
        List<Long> idList = ConvertUtil.str2longs(ids);
        applyAccountService.batchDelApplyAccount(idList);
        return new JsonResult().success();
    }

    @GetMapping(MODEL + "/process.do")
    @Function("cms.applyAccount.edit")
    @ResponseBody
    public ModelAndView processs(Long id) {
        ModelAndView view = new ModelAndView("/cms/applyAccount/process.html");
        CoreUser user = userConsoleService.queryUserById(id);
        view.addObject("user", user);
        return view;
    }

}
